package com.leo.tool.jdk.jdk4.bio;

import lombok.Cleanup;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

@Slf4j
public class Server {

    public static void main(String[] args) throws IOException {
        @Cleanup
        ServerSocket server = new ServerSocket(8000);
        while (true) {
            // 等待建立链接
            // 线程为RUNNING状态阻塞
            Socket socket = server.accept();
            // 一个链接用一个线程等待数据请求，大量线程浪费
            new Thread(() -> execute(socket)).start();
        }
    }


    @SneakyThrows
    private static void execute(Socket socket) {
        InputStream inputStream = socket.getInputStream();
        OutputStream outputStream = socket.getOutputStream();
        byte[] buff = new byte[1024];

        while (!socket.isClosed()) {
            // 等待数据传输完成
            // 线程为RUNNING状态阻塞
            int len = inputStream.read(buff);
            String content = new String(buff, 0, len);
            log.info(content);

            if ("bye".equals(content)) {
                outputStream.write("bye".getBytes());
                outputStream.flush();
                break;
            } else {
                outputStream.write("hello".getBytes());
                outputStream.flush();
            }
        }
        socket.close();
    }

}
